from sonto.list import List, Node


class FIFO(List):
    def __init__(self, max_length=None):
        self.max_length = max_length
        List.__init__(self)

    def is_empty(self):
        return self.length == 0

    def is_full(self):
        return self.length == self.max_length

    def unshift(self, data):
        assert not self.is_full()
        node = Node()
        node.data = data

        pNode = self.tail.prev
        pNode.next = node
        node.prev = pNode

        self.tail.prev = node
        node.next = self.tail
        self.length += 1

    def shift(self):
        assert not self.is_empty()
        node = self.head.next
        nNode = node.next

        self.head.next = nNode
        nNode.prev = self.head
        self.length -= 1

        return node.data

    def __iter__(self):
        node = self.head.next
        while node != self.tail:
            yield node.data
            node = node.next

    def __len__(self):
        return self.length


if __name__ == "__main__":
    l = FIFO(10)

    for i in range(0, 10):
        l.unshift(i)

    for i in l:
        print(i)

    try:
        print("The count: %d" % (len(l)))
        l.unshift(100)
    except Exception:
        print("The FIFO is full")
        data = l.shift()
        print("The first data is: %d" % (data))
        l.unshift(100)
        print("Access every element.")
        for i in l:
            print(i)
